<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use think\Db;
use app\common\controller\Api;
use app\common\model\Order as OrderModel;
use app\admin\model\Play as PlayModel;
use app\common\model\OrderLog;
use app\api\service\UserService;
use app\common\model\User;
use app\common\model\OrderAftersale;
use app\common\model\IncompleteBill;
use app\common\model\OrderProof;
use app\api\service\OrderService;

class Yunzhan extends Api
{

    protected $noNeedLogin = ['*'];
    protected $noNeedRight = '*';
    protected $layout = '';
    
    public function index()
    {
        return $this->view->fetch();
    }

    /**
     * 饿了么订单列表
     * @return [type] [description]
     */
    public function getOrderList($page,$page_size,$date_type,$start_date,$end_date,$state,$biz_unit=2,$order_id='',$flow_type='',$settle_state='')
    {
        $Obj = new \services\ElemService();
        $param = [
          'biz_unit'=>$biz_unit, //1-CPA 2-CPS
          'page_size'=>$page_size,
          'page_number'=>$page,
          'start_date' => $start_date,
          'end_date' => $end_date,
          'date_type' => $date_type,
        ];
        if ($state!=5) {
            $param['order_state'] = $state;
        }
        if ($flow_type) {
            $param['flow_type'] = $flow_type;
        }
        if ($order_id) {
            $param['order_id'] = $order_id;
        }
        if ($settle_state) {
            $param['settle_state'] = $settle_state;
        }
        $res = $Obj->getOrderList($param);
        $decode = json_decode($res,1);
        if (isset($decode['alibaba_alsc_union_kbcpx_positive_order_get_response']['result']['order_detail_report_d_t_o']) && $decode['alibaba_alsc_union_kbcpx_positive_order_get_response']['result']['order_detail_report_d_t_o']) {
            Db::startTrans();
            // try {
                $order_detail_report_d_t_o = $decode['alibaba_alsc_union_kbcpx_positive_order_get_response']['result']['order_detail_report_d_t_o'];
                foreach ($order_detail_report_d_t_o as $key => $value) {
                    // if (!isset($value['activity_id']) || !$value['activity_id']) continue;
                    $ext_info = json_decode($value['ext_info'],1);
                    if (!isset($ext_info['lockId']) || !$ext_info['lockId']) continue;
                    $lockId = $ext_info['lockId'];
                    if ($value['order_state']==2) {//已下单
                        $mtofficial_order = \app\common\model\Mtorder::where(['wm_order_sn'=>$lockId])->find();
                        if (!$mtofficial_order || $mtofficial_order['order_status']!=1) continue;
                        $content = json_decode($mtofficial_order['content'],1);
                        if (!$content) $content = [];
                        $content['source'] = 5;
                        list($play,$shop) = (new \app\api\service\PlayService())->newmtofficial($mtofficial_order['play_no'],$mtofficial_order['cps_id'],$content);
                        $mtofficial_order->shop_no = $value['biz_order_id'];
                        $mtofficial_order->user_pay = (float)$value['pay_amount'];
                        $mtofficial_order->actual_rebate_amt = floatval($play['back_money']);
                        $mtofficial_order->rebate_amt = (float)$value['income'];
                        $mtofficial_order->service_charge_amt = $play['service_amt'];
                        $mtofficial_order->pay_time = strtotime($value['pay_time']);
                        $mtofficial_order->expire_time = strtotime(date('Y-m-d'))+86400*2-1;  // 报名后过期时间第二天24点
                        // 如果实付不满，就取消订单
                        if ($value['pay_amount']<$play['user_pay']) {
                            $mtofficial_order->order_status=-4;
                            $ElemService = new \services\ElemService('');
                            $res = $ElemService->stockrelease($mtofficial_order['wm_order_sn']);
                        } else {
                            $mtofficial_order->order_status=4;
                        }
                        $mtofficial_order->save();
                    } elseif ($value['order_state']==4 && $value['flow_type']==3) {// 已收货
                        $mtofficial_order = \app\common\model\Mtorder::where(['wm_order_sn'=>$lockId])->find();
                        if (!$mtofficial_order || $mtofficial_order['order_status']!=1) continue;
                        $content = json_decode($mtofficial_order['content'],1);
                        if (!$content) $content = [];
                        $content['source'] = 5;
                        list($play,$shop) = (new \app\api\service\PlayService())->newmtofficial($mtofficial_order['play_no'],$mtofficial_order['cps_id'],$content);
                        $mtofficial_order->shop_no = $value['biz_order_id'];
                        $mtofficial_order->user_pay = (float)$value['pay_amount'];
                        $mtofficial_order->actual_rebate_amt = floatval($play['back_money']);
                        $mtofficial_order->rebate_amt = (float)$value['income'];
                        $mtofficial_order->service_charge_amt = $play['service_amt'];
                        $mtofficial_order->pay_time = strtotime($value['pay_time']);
                        $mtofficial_order->expire_time = strtotime(date('Y-m-d'))+86400*2-1;  // 报名后过期时间第二天24点
                        // 如果实付不满，就取消订单
                        if ($value['pay_amount']<$play['user_pay']) {
                            $mtofficial_order->order_status=-4;
                            $ElemService = new \services\ElemService('');
                            $res = $ElemService->stockrelease($mtofficial_order['wm_order_sn']);
                        } else {
                            $mtofficial_order->order_status=4;
                        }
                        $mtofficial_order->save();
                    } elseif ($value['order_state']==4 && $value['settle_state']==-99) {// 无需结算
                        $mtofficial_order = \app\common\model\Mtorder::where(['wm_order_sn'=>$lockId])->find();
                        if (!$mtofficial_order || $mtofficial_order['order_status']!=1) continue;
                        $content = json_decode($mtofficial_order['content'],1);
                        if (!$content) $content = [];
                        $content['source'] = 5;
                        list($play,$shop) = (new \app\api\service\PlayService())->newmtofficial($mtofficial_order['play_no'],$mtofficial_order['cps_id'],$content);
                        $mtofficial_order->shop_no = $value['biz_order_id'];
                        $mtofficial_order->user_pay = (float)$value['pay_amount'];
                        $mtofficial_order->actual_rebate_amt = floatval($play['back_money']);
                        $mtofficial_order->rebate_amt = (float)$value['income'];
                        $mtofficial_order->service_charge_amt = $play['service_amt'];
                        $mtofficial_order->pay_time = strtotime($value['pay_time']);
                        $mtofficial_order->order_status=99;
                        $mtofficial_order->save();
                    } elseif ($value['order_state']==4 && $value['flow_type']==26) {//已完成
                        $mtofficial_order = \app\common\model\Mtorder::where(['wm_order_sn'=>$lockId])->find();
                        if (!$mtofficial_order || $mtofficial_order['order_status']==3 || $mtofficial_order['order_status']==-3) continue;
                        if ($mtofficial_order->service_charge_amt==0) {
                            $content = json_decode($mtofficial_order['content'],1);
                            if (!$content) $content = [];
                            $content['source'] = 5;
                            list($play,$shop) = (new \app\api\service\PlayService())->newmtofficial($mtofficial_order['play_no'],$mtofficial_order['cps_id'],$content);
                            $mtofficial_order->service_charge_amt = $play['service_amt'];
                        }
                        $mtofficial_order->shop_no = $value['biz_order_id'];
                        $mtofficial_order->user_pay = (float)$value['pay_amount'];
                        $mtofficial_order->actual_rebate_amt = floatval($value['settle']-$value['activity_fee']-$mtofficial_order->service_charge_amt);
                        if ($mtofficial_order->actual_rebate_amt<0) $mtofficial_order->actual_rebate_amt=0;
                        $mtofficial_order->rebate_amt = floatval($value['settle']-$value['activity_fee']);
                        if ($mtofficial_order->rebate_amt<0) $mtofficial_order->rebate_amt=0;
                        $mtofficial_order->pay_time = strtotime($value['pay_time']);
                        $mtofficial_order->order_status = 3;
                        $mtofficial_order->save();
                        $User = new \app\common\model\User();
                        $user = \app\common\model\User::where('id',$mtofficial_order['user_id'])->find();
                        // 用户获得吃豆
                        $beans = $mtofficial_order['actual_rebate_amt'];
                        $user->beans($beans,$mtofficial_order['user_id'],'下单返豆',$mtofficial_order['play_order_no']);
                        \app\common\model\MtorderLog::create([
                            'play_order_id' => $mtofficial_order['id'],
                            'play_order_no' => $mtofficial_order['play_order_no'],
                            // 'create_by' => $nickname,
                            'create_by_id' => $mtofficial_order['user_id'],
                            'is_front' => 1,
                            'info' => '订单完成',
                        ]);
                        // 发送微信消息
                        $qywx = Db::name('qywx_receive')->where('user_id',$user['id'])->field('id,UserID,ExternalUserID')->find();
                        if ($qywx) {
                            $external_userid = $qywx['ExternalUserID'];
                            $sender = $qywx['UserID'];
                            $title = '您的活动订单审核成功';
                            $picurl = config('upload_domain').'/uploads/20230422/baca91c2f33a6d1270aae65ea4d3dc79.png';
                            $desc = '恭喜完成订单，获得'.$beans.'吃豆';
                            $url = config('h5_domain').'/#/pages/index/order';
                            $lPublics = new \app\api\service\UserService();
                            $res = $lPublics->qywxPush($external_userid,$sender,$title,$picurl,$desc,$url,$user['id']);
                        }
                        // 发送app消息
                        $lPublics = new \app\api\service\UserService();
                        $title = '您的活动订单审核成功';
                        $desc = '恭喜完成订单，获得'.$beans.'吃豆';
                        $url = '/pages/index/order';
                        $res = $lPublics->pushChat($user['birthday'],$title,$desc,$url,$user['id'],$mtofficial_order->play_order_no);
                        $title = '【完成一笔订单】任务达成';
                        $desc = '获得2次抽奖机会（当日有效）';
                        $url = '/index/raffle/raffle';
                        $res = $lPublics->pushChat($user['birthday'],$title,$desc,$url,$user['id']);
                        // 分销和抽奖机会和积分
                        if ($user['pid']) {
                            $order_num = order_count($mtofficial_order['user_id']);
                            if ($order_num==1) {
                                $amount = (int)Db::name('config')->where('name','first_order')->value('value');
                                // 上级用户新增有效团员
                                \app\common\model\UserLuckdrawLog::addLog($user['pid'], 1, $mtofficial_order['play_order_no'], '新增有效团员');
                                // 如果是第一单，则上级用户获得一个有效用户，加积分
                                $res = $User->score(config('invite_score'),$user['pid'],'邀请获得');
                                if (!$res) {Db::rollback();$this->error('上级用户获取积分失败');}
                                // unipush
                                $user2 = $User->get($user['pid']);
                                // if (isset($user2['birthday']) && $user2['birthday']) {
                                    $lPublics = new \app\api\service\UserService();
                                    $title = '【新增一位有效团员】任务达成';
                                    $desc = '获得1次抽奖机会（当日有效）';
                                    $url = '/index/raffle/raffle';
                                    $res = $lPublics->pushChat($user2['birthday'],$title,$desc,$url,$user2['id']);
                                // }
                            } elseif ($order_num==2) {
                                $amount = (int)Db::name('config')->where('name','second_order')->value('value');
                            } else {
                                $rate = (int)\think\Config::get('site.third_order');
                                $amount = round($mtofficial_order['service_charge_amt']*$rate*0.01,2);
                                // 当前是不是会员团长
                                $user1 = \app\common\model\User::get($user['pid']);
                                if ($user1['hytz']==1) {
                                    // 团长的有效用户数是否大于指定的用户数
                                    $invitation_new_reward = \think\Config::get('site.yyty');
                                    $user_distribution = Db::name('user_distribution')->field('uid')->where(['pid'=>$user['pid'],'status'=>1])->group('uid')->select();
                                    if (count($user_distribution)>$invitation_new_reward) {
                                        $ratenim = (float)\think\Config::get('site.third_order_min3');
                                    } else {
                                        $ratenim = (float)\think\Config::get('site.third_order_min2');
                                    }
                                } else {
                                    $ratenim = (float)\think\Config::get('site.third_order_min');
                                }
                                if ($amount<$ratenim) $amount = $ratenim;
                            }
                            if ($amount) {
                                \app\common\model\UserDistribution::create([
                                    'play_order_no' => $mtofficial_order['play_order_no'],
                                    'uid' => $mtofficial_order['user_id'],
                                    'pid' => $user['pid'],
                                    'play_no' => $mtofficial_order['play_no'],
                                    'amount' => $amount,
                                    'order_times' => $order_num,
                                ]);
                                // 上级用户加吃豆
                                $res = $User->beans($amount, $user['pid'], '下级返利', $mtofficial_order['play_order_no']);
                                if (!$res) {Db::rollback();$this->error('上级返利失败');}
                                // 发送app消息
                                // $user = \app\common\model\User::get($user['pid']);
                                if (!isset($user1)) $user1 = \app\common\model\User::get($user['pid']);
                                // if (isset($user['birthday']) && $user['birthday']) {
                                    $lPublics = new \app\api\service\UserService();
                                    $title = '团长奖励获得吃豆';
                                    $desc = '您的好友'.$user['nickname'].'完成第'.$order_num.'单，奖励您'.$amount.'吃豆';
                                    $url = '/pages/user/user-data';
                                    $res = $lPublics->pushChat($user1['birthday'],$title,$desc,$url,$user1['id']);
                                // }
                            }
                        }
                        // 用户加积分
                        $res = $User->score(config('order_score'),$mtofficial_order['user_id'],'下单获得');
                        if (!$res) {Db::rollback();return false;}
                        // 完成订单
                        \app\common\model\UserLuckdrawLog::addLog($mtofficial_order['user_id'], 1, $mtofficial_order['play_order_no'], '完成订单', 2);
                    }
                }
                Db::commit();
            // } catch (\Exception $e) {
            //     Db::rollback();
            //     return $e->getMessage();
            // }
            if ($decode['alibaba_alsc_union_kbcpx_positive_order_get_response']['total_count']>=$page_size) {
                $page += 1;
                $this->getOrderList($page,$page_size,$date_type,$start_date,$end_date,$state,$biz_unit,$order_id,$flow_type);
            }
        }
        return true;
    }

    /**
     * 已下单列表
     * @param  string $value [description]
     * @return [type]        [description]
     */
    public function getRegisteredList()
    {
        $page = 1;
        $page_size = 50;
        $date_type = 2; // 时间维度，1-付款时间 2-创建时间 3-结算时间 4-更新时间
        $start_date = date('Y-m-d H:i:s',time()-10800);
        $end_date = date('Y-m-d H:i:s',time());
        $state = 2; // 订单状态，0-已失效 1-已下单 2-已付款 4-已收货 5-全部状态
        $flow_type = 3;//场景值，支持多场景（英文逗号分隔）查询7卡券订单，8卡券核销订单，10-媒体出资CPS红包，11-媒体出资霸王餐加码红包，26-评价有礼订单
        $order_id = '';
        $biz_unit=2;//1-CPA 2-CPS
        $res = $this->getOrderList($page,$page_size,$date_type,$start_date,$end_date,$state,$biz_unit,$order_id);
        if ($res!==true) {
            echo $res;
        }
    }

    /**
     * 已收货列表
     * @param  string $value [description]
     * @return [type]        [description]
     */
    public function getReceivedList()
    {
        $page = 1;
        $page_size = 50;
        $date_type = 2; // 时间维度，1-付款时间 2-创建时间 3-结算时间 4-更新时间
        $start_date = date('Y-m-d H:i:s',time()-10800);
        $end_date = date('Y-m-d H:i:s',time());
        $state = 4; // 订单状态，0-已失效 1-已下单 2-已付款 4-已收货 5-全部状态
        $flow_type = 3;//场景值，支持多场景（英文逗号分隔）查询7卡券订单，8卡券核销订单，10-媒体出资CPS红包，11-媒体出资霸王餐加码红包，26-评价有礼订单
        $order_id = '';
        $biz_unit=2;//1-CPA 2-CPS
        $res = $this->getOrderList($page,$page_size,$date_type,$start_date,$end_date,$state,$biz_unit,$order_id);
        if ($res!==true) {
            echo $res;
        }
    }

    /**
     * 已完成列表
     * @param  string $value [description]
     * @return [type]        [description]
     */
    public function getCompletedList()
    {
        $page = 1;
        $page_size = 50;
        $date_type = 3; // 时间维度，1-付款时间 2-创建时间 3-结算时间 4-更新时间
        $start_date = date('Y-m-d H:i:s',time()-3600);
        $end_date = date('Y-m-d H:i:s',time());
        $state = 4; // 订单状态，0-已失效 1-已下单 2-已付款 4-已收货 不传-全部状态
        $flow_type = 26;//场景值，支持多场景（英文逗号分隔）查询7卡券订单，8卡券核销订单，10-媒体出资CPS红包，11-媒体出资霸王餐加码红包，26-评价有礼订单
        $biz_unit=1;//1-CPA 2-CPS
        $order_id = '';
        $settle_state=1;//结算状态，1-已结算 2-未结算 不传-全部状态
        $res = $this->getOrderList($page,$page_size,$date_type,$start_date,$end_date,$state,$biz_unit,$order_id,$flow_type,$settle_state);
        if ($res!==true) {
            echo $res;
        }
    }


    public function notify()
    {
        $params = $this->request->param();
        \think\Log::write('报名回调'.json_encode($params));
        $nickname='三方商家';
        $id=999;
        // $param = '{"order_sn":"M240522211129C83857","user_order_sn":"2001084183633225009","paid_amount":"26.18","commission_type":"2","commission":"0.00","commission_ratio":"0.00","e_commission":"16.00","e_commission_ratio":"61.11","state":"1","internal_state":"4","source":"1","user_source":"","promotion_id":"yz-68197110-145818-170907","reason":"","expire_time":"1716393599","create_time":"2024-05-22 21:11:30","place_order_time":"2024-05-22 21:43:10","finished_time":"","reject_type":"0","update_time":"2024-05-22 21:43:10"}';
        // $params = json_decode($param,1);
        if ($params['source']!=2) {
            $platform_order_no = $params['order_sn'];
            $mtofficial_order = \app\common\model\Mtorder::where(['play_order_no'=>$platform_order_no])->find();
            if (isset($mtofficial_order['content']) && $mtofficial_order['content']) {
                $content = json_decode($mtofficial_order['content'],1);
            }
            if (isset($content['shop_origin_id']) && $mtofficial_order) {
                list($play,$shop) = (new \app\api\service\PlayService())->mtofficial($mtofficial_order['play_no'],$mtofficial_order['cps_id'],$content);
                //用户任务状态编码(状态  1：已报名 2：审核中 3：已完成 4已驳回 5 已取消 6已过期)
                switch ($params['state']) {
                    case 6:
                        $mtofficial_order->order_status=-2;
                        break;
                    case 5:
                        $mtofficial_order->order_status=-1;
                        break;
                    case 1:
                        if ($params['internal_state']==4) {
                            $mtofficial_order->user_pay = (float)$params['paid_amount'];
                            if ($mtofficial_order['is_yunzhan']!=3) {
                                $ratio = $play['ratio']/100;
                                $actual_rebate_amt = round($params['paid_amount']*$ratio/100,2);
                                $maxCommission = $play['maxCommission']/100;
                                if ($actual_rebate_amt>$maxCommission) {
                                    $actual_rebate_amt = $maxCommission;
                                }
                                $mtofficial_order->actual_rebate_amt = (float)$actual_rebate_amt;
                                $mtofficial_order->rebate_amt = (float)$params['commission'];
                                $mtofficial_order->service_charge_amt = round($params['commission']-$actual_rebate_amt,2);
                            } else {
                                $mtofficial_order->actual_rebate_amt = (float)$params['commission']-$play['service_amt'];
                                $mtofficial_order->rebate_amt = (float)$params['commission'];
                                $mtofficial_order->service_charge_amt = $play['service_amt'];
                            }
                            $mtofficial_order->pay_time = strtotime($params['place_order_time']);
                            $mtofficial_order->expire_time = strtotime(date('Y-m-d'))+86400*2-1;
                            // 过期时间最晚到第二天0点
                            // $dayend = strtotime(date('Y-m-d'))+86400*2-1;
                            // if ($mtofficial_order->expire_time>$dayend) {
                            //     $mtofficial_order->expire_time=$dayend;
                            // }
                            $mtofficial_order->order_status=4;
                            $mtofficial_order->crood_type = isset($params['user_order_sn'])?$params['user_order_sn']:'';
                        } elseif ($params['internal_state']==3) {
                            $mtofficial_order->user_pay = 0;
                            $ratio = $play['ratio']/100;
                            $actual_rebate_amt = round($params['paid_amount']*$ratio/100,2);
                            $maxCommission = $play['maxCommission']/100;
                            if ($actual_rebate_amt>$maxCommission) {
                                $actual_rebate_amt = $maxCommission;
                            }
                            $mtofficial_order->actual_rebate_amt = (float)$actual_rebate_amt;
                            $mtofficial_order->rebate_amt = (float)$params['commission'];
                            $mtofficial_order->service_charge_amt = round($params['commission']-$actual_rebate_amt,2);
                            $mtofficial_order->pay_time = 0;
                            $mtofficial_order->expire_time = time() + 21600;
                            // 过期时间最晚到第二天0点
                            $dayend = strtotime(date('Ymd'))+86399;
                            if ($mtofficial_order->expire_time>$dayend) {
                                $mtofficial_order->expire_time=$dayend;
                            }
                            $mtofficial_order->order_status=1;
                        }
                        break;
                    case 2:
                        if ($params['internal_state']==4) {
                            $mtofficial_order->user_pay = (float)$params['paid_amount'];
                            $ratio = $play['ratio']/100;
                            $actual_rebate_amt = round($params['paid_amount']*$ratio/100,2);
                            $maxCommission = $play['maxCommission']/100;
                            if ($actual_rebate_amt>$maxCommission) {
                                $actual_rebate_amt = $maxCommission;
                            }
                            $mtofficial_order->actual_rebate_amt = (float)$actual_rebate_amt;
                            $mtofficial_order->rebate_amt = (float)$params['commission'];
                            $mtofficial_order->service_charge_amt = round($params['commission']-$actual_rebate_amt,2);
                            $mtofficial_order->pay_time = strtotime($params['place_order_time']);
                            $mtofficial_order->expire_time = strtotime(date('Y-m-d'))+86400*2-1;  // 报名后过期时间第二天24点
                            $mtofficial_order->order_status=4;
                        }
                        break;
                    case 3:
                        if ($mtofficial_order->order_status==3) {
                            $this->error('状态有误');
                        }
                        $mtofficial_order->user_pay = (float)$params['paid_amount'];
                        if ($mtofficial_order['is_yunzhan']!=3) {
                            $ratio = $play['ratio']/100;
                            $actual_rebate_amt = round($params['paid_amount']*$ratio/100,2);
                            $maxCommission = $play['maxCommission']/100;
                            if ($actual_rebate_amt>$maxCommission) {
                                $actual_rebate_amt = $maxCommission;
                            }
                            $mtofficial_order->actual_rebate_amt = (float)$actual_rebate_amt;
                            $mtofficial_order->rebate_amt = (float)$params['commission'];
                            $mtofficial_order->service_charge_amt = round($params['commission']-$actual_rebate_amt,2);
                        } else {
                            $mtofficial_order->actual_rebate_amt = (float)$params['commission']-$play['service_amt'];
                            $mtofficial_order->rebate_amt = (float)$params['commission'];
                            $mtofficial_order->service_charge_amt = $play['service_amt'];
                        }
                        $mtofficial_order->pay_time = strtotime($params['place_order_time']);
                        $mtofficial_order->order_status=3;
                        break;
                }
                Db::startTrans();
                try {
                    if ($mtofficial_order['actual_rebate_amt']>100) {
                        $this->error('提交有误');exit;
                    }
                    $mtofficial_order->save();
                    if (in_array($params['state'], [3])) {
                        $User = new \app\common\model\User();
                        $user = \app\common\model\User::where('id',$mtofficial_order['user_id'])->find();
                        // 用户获得吃豆
                        $beans = $mtofficial_order['actual_rebate_amt'];
                        $user->beans($beans,$mtofficial_order['user_id'],'下单返豆',$mtofficial_order['play_order_no']);
                        \app\common\model\MtorderLog::create([
                            'play_order_id' => $mtofficial_order['id'],
                            'play_order_no' => $mtofficial_order['play_order_no'],
                            // 'create_by' => $nickname,
                            'create_by_id' => $mtofficial_order['user_id'],
                            'is_front' => 1,
                            'info' => '订单完成',
                        ]);
                        // 发送微信消息
                        $qywx = Db::name('qywx_receive')->where('user_id',$user['id'])->field('id,UserID,ExternalUserID')->find();
                        if ($qywx) {
                            $external_userid = $qywx['ExternalUserID'];
                            $sender = $qywx['UserID'];
                            $title = '您的活动订单审核成功';
                            $picurl = config('upload_domain').'/uploads/20230422/baca91c2f33a6d1270aae65ea4d3dc79.png';
                            $desc = '恭喜完成订单，获得'.$beans.'吃豆';
                            $url = config('h5_domain').'/#/pages/index/order';
                            $lPublics = new \app\api\service\UserService();
                            $res = $lPublics->qywxPush($external_userid,$sender,$title,$picurl,$desc,$url,$user['id']);
                        }
                        // 发送app消息
                        // if (isset($user['birthday']) && $user['birthday']) {
                            $lPublics = new \app\api\service\UserService();
                            $title = '您的活动订单审核成功';
                            $desc = '恭喜完成订单，获得'.$beans.'吃豆';
                            $url = '/pages/index/order';
                            $res = $lPublics->pushChat($user['birthday'],$title,$desc,$url,$user['id'],$mtofficial_order->play_order_no);
                            $title = '【完成一笔订单】任务达成';
                            $desc = '获得2次抽奖机会（当日有效）';
                            $url = '/index/raffle/raffle';
                            $res = $lPublics->pushChat($user['birthday'],$title,$desc,$url,$user['id']);
                        // }
                        // 分销和抽奖机会和积分
                        // if ($order->order_status==3) {
                            if ($user['pid']) {
                                $order_num = order_count($mtofficial_order['user_id']);
                                if ($order_num==1) {
                                    $amount = (int)Db::name('config')->where('name','first_order')->value('value');
                                    // 上级用户新增有效团员
                                    \app\common\model\UserLuckdrawLog::addLog($user['pid'], 1, $mtofficial_order['play_order_no'], '新增有效团员');
                                    // 如果是第一单，则上级用户获得一个有效用户，加积分
                                    $res = $User->score(config('invite_score'),$user['pid'],'邀请获得');
                                    if (!$res) {Db::rollback();$this->error('上级用户获取积分失败');}
                                    // unipush
                                    $user2 = $User->get($user['pid']);
                                    // if (isset($user2['birthday']) && $user2['birthday']) {
                                        $lPublics = new \app\api\service\UserService();
                                        $title = '【新增一位有效团员】任务达成';
                                        $desc = '获得1次抽奖机会（当日有效）';
                                        $url = '/index/raffle/raffle';
                                        $res = $lPublics->pushChat($user2['birthday'],$title,$desc,$url,$user2['id']);
                                    // }
                                } elseif ($order_num==2) {
                                    $amount = (int)Db::name('config')->where('name','second_order')->value('value');
                                } else {
                                    $rate = (int)\think\Config::get('site.third_order');
                                    $amount = round($mtofficial_order['service_charge_amt']*$rate*0.01,2);
                                    // 当前是不是会员团长
                                    $user1 = \app\common\model\User::get($user['pid']);
                                    if ($user1['hytz']==1) {
                                        // 团长的有效用户数是否大于指定的用户数
                                        $invitation_new_reward = \think\Config::get('site.yyty');
                                        $user_distribution = Db::name('user_distribution')->field('uid')->where(['pid'=>$user['pid'],'status'=>1])->group('uid')->select();
                                        if (count($user_distribution)>$invitation_new_reward) {
                                            $ratenim = (float)\think\Config::get('site.third_order_min3');
                                        } else {
                                            $ratenim = (float)\think\Config::get('site.third_order_min2');
                                        }
                                    } else {
                                        $ratenim = (float)\think\Config::get('site.third_order_min');
                                    }
                                    if ($amount<$ratenim) $amount = $ratenim;
                                }
                                if ($amount) {
                                    \app\common\model\UserDistribution::create([
                                        'play_order_no' => $mtofficial_order['play_order_no'],
                                        'uid' => $mtofficial_order['user_id'],
                                        'pid' => $user['pid'],
                                        'play_no' => $mtofficial_order['play_no'],
                                        'amount' => $amount,
                                        'order_times' => $order_num,
                                    ]);
                                    // 上级用户加吃豆
                                    $res = $User->beans($amount, $user['pid'], '下级返利', $mtofficial_order['play_order_no']);
                                    if (!$res) {Db::rollback();$this->error('上级返利失败');}
                                    // 发送app消息
                                    // $user = \app\common\model\User::get($user['pid']);
                                    if (!isset($user1)) $user1 = \app\common\model\User::get($user['pid']);
                                    // if (isset($user['birthday']) && $user['birthday']) {
                                        $lPublics = new \app\api\service\UserService();
                                        $title = '团长奖励获得吃豆';
                                        $desc = '您的好友'.$user['nickname'].'完成第'.$order_num.'单，奖励您'.$amount.'吃豆';
                                        $url = '/pages/user/user-data';
                                        $res = $lPublics->pushChat($user1['birthday'],$title,$desc,$url,$user1['id']);
                                    // }
                                }
                            }
                            // 用户加积分
                            $res = $User->score(config('order_score'),$mtofficial_order['user_id'],'下单获得');
                            if (!$res) {Db::rollback();$this->error('增加积分失败');}
                            // 完成订单
                            \app\common\model\UserLuckdrawLog::addLog($mtofficial_order['user_id'], 1, $mtofficial_order['play_order_no'], '完成订单', 2);
                        // }
                    }
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                }
            }
        } else {
            Db::startTrans();
            try {
                // 三方招商，待商家复审完成
                $row = OrderModel::where('yunzhan_order_no',$params['order_sn'])->find();
                $play_order_no = $params['order_sn'];
                if (isset($row['order_status']) && $row['order_status']==6 && $params['state']==3) {
                    $User = new \app\common\model\User();
                    $play = PlayModel::where(['play_no'=>$row['play_no']])->lock(true)->find();
                    $orderProof = OrderProof::where(['play_order_no'=>$play_order_no])->order('id DESC')->find();
                    if (!$orderProof) {
                        $this->error('提交有误');
                    }
                    $beans = $row->actual_rebate_amt;
                    $User->beans($beans,$row['user_id'],'下单返豆',$orderProof['play_order_no']);
                    // 实际返豆
                    $row->actual_rebate_amt = $beans;
                    // 订单状态
                    $row->order_status = 3;
                    $row->update_by = $id;
                    $row->save();
                    $this->orderLog($row->id,$play_order_no,'客服审核通过',$nickname,$id);
                    // 消息处理
                    $user = $User->get($row['user_id']);
                    // 发送微信消息
                    $qywx = Db::name('qywx_receive')->where('user_id',$user['id'])->field('id,UserID,ExternalUserID')->find();
                    if ($qywx) {
                        $external_userid = $qywx['ExternalUserID'];
                        $sender = $qywx['UserID'];
                        $title = '您的活动订单审核成功';
                        $picurl = config('upload_domain').'/uploads/20230422/baca91c2f33a6d1270aae65ea4d3dc79.png';
                        $desc = '恭喜完成订单，获得'.$beans.'吃豆';
                        $url = config('h5_domain').'/#/pages/index/order';
                        $lPublics = new \app\api\service\UserService();
                        $res = $lPublics->qywxPush($external_userid,$sender,$title,$picurl,$desc,$url,$user['id']);
                    }
                    // 发送app消息
                    // if (isset($user['birthday']) && $user['birthday']) {
                        $lPublics = new \app\api\service\UserService();
                        $title = '您的活动订单审核成功';
                        $desc = '恭喜完成订单，获得'.$beans.'吃豆';
                        $url = '/pages/index/order';
                        $res = $lPublics->pushChat($user['birthday'],$title,$desc,$url,$user['id'],$play_order_no);
                        $title = '【完成一笔订单】任务达成';
                        $desc = '获得2次抽奖机会（当日有效）';
                        $url = '/index/raffle/raffle';
                        $res = $lPublics->pushChat($user['birthday'],$title,$desc,$url,$user['id']);
                    // }
                    // 发送短信
                    // if (isset($user['mobile']) && $user['mobile']) {
                    //     $Alisms = new \addons\alisms\Alisms();
                    //     $params = [
                    //         'mobile' => $user['mobile'],
                    //         'event' => 'order_complete',
                    //         'msg' => '您好，您在吃喝不愁平台参加的外卖活动订单已通过，请知晓。',
                    //     ];
                    //     $Alisms->smsNotice($params);
                    // }
                    // 订阅消息
                    $openid = Db::name('third')->where(['user_id'=>$user['id'],'platform'=>'miniprogram'])->value('openid');
                    if ($openid) {
                        $UserService = new \app\api\service\UserService();
                        $template_id = config('template_id.ddwctz');
                        $page = '/pages/index/order';
                        $data = [
                            'thing1' => ['value'=>$row->shop_name],
                            'time3' => ['value'=>date('Y-m-d H:i:s')],
                            'character_string5' => ['value'=>$play_order_no],
                            'phrase10' => ['value'=>'已完成'],
                        ];
                        $res = $UserService->xcxNotice($openid,$template_id,$page,$data);
                    }
                    // 分销和抽奖机会和积分
                    if ($row->order_status==3) {
                        // 中间人佣金
                        if ($play['is_pay']==1) {
                            $shop = Db::name('shop')->where(['shop_no'=>$row['shop_no']])->field('middleman_id,shop_no')->find();
                            $middleman = Db::name('middleman')->where(['id'=>$shop['middleman_id']])->field('rebate_amt,user_id')->find();
                            if (isset($middleman['rebate_amt']) && $middleman['rebate_amt']) {
                                (new \app\common\model\User())->money($middleman['rebate_amt'], $middleman['user_id'], '经纪人收益', $play_order_no);
                            }
                        }
                        $this->orderLog($row->id,$play_order_no,'订单完成',$nickname,$id);
                        if ($user['pid']) {
                            $order_num = order_count($row['user_id']);
                            if ($order_num==1) {
                                $amount = (int)Db::name('config')->where('name','first_order')->value('value');
                                // 上级用户新增有效团员
                                \app\common\model\UserLuckdrawLog::addLog($user['pid'], 1, $play_order_no, '新增有效团员');
                                // 如果是第一单，则上级用户获得一个有效用户，加积分
                                $res = (new User())->score(config('invite_score'),$user['pid'],'邀请获得');
                                if (!$res) {Db::rollback();return false;}
                                // unipush
                                $user2 = $User->get($user['pid']);
                                if (isset($user2['birthday']) && $user2['birthday']) {
                                    $lPublics = new \app\api\service\UserService();
                                    $title = '【新增一位有效团员】任务达成';
                                    $desc = '获得1次抽奖机会（当日有效）';
                                    $url = '/index/raffle/raffle';
                                    $res = $lPublics->pushChat($user2['birthday'],$title,$desc,$url,$user2['id']);
                                }
                            } elseif ($order_num==2) {
                                $amount = (int)Db::name('config')->where('name','second_order')->value('value');
                            } else {
                                $rate = (int)\think\Config::get('site.third_order');
                                $amount = round($row['service_charge_amt']*$rate*0.01,2);
                                // 当前是不是会员团长
                                $user1 = \app\common\model\User::get($user['pid']);
                                if ($user1['hytz']==1) {
                                    // 团长的有效用户数是否大于指定的用户数
                                    $invitation_new_reward = \think\Config::get('site.yyty');
                                    $user_distribution = Db::name('user_distribution')->field('uid')->where(['pid'=>$user['pid'],'status'=>1])->group('uid')->select();
                                    if (count($user_distribution)>$invitation_new_reward) {
                                        $ratenim = (float)\think\Config::get('site.third_order_min3');
                                    } else {
                                        $ratenim = (float)\think\Config::get('site.third_order_min2');
                                    }
                                } else {
                                    $ratenim = (float)\think\Config::get('site.third_order_min');
                                }
                                if ($amount<$ratenim) $amount = $ratenim;
                            }
                            if ($amount) {
                                \app\common\model\UserDistribution::create([
                                    'play_order_no' => $play_order_no,
                                    'uid' => $row['user_id'],
                                    'pid' => $user['pid'],
                                    'play_no' => $row['play_no'],
                                    'amount' => $amount,
                                    'order_times' => $order_num,
                                ]);
                                // 上级用户加吃豆
                                $res = (new User())->beans($amount, $user['pid'], '下级返利', $play_order_no);
                                if (!$res) {Db::rollback();return false;}
                                // 发送app消息
                                if (!isset($user1)) $user1 = \app\common\model\User::get($user['pid']);
                                // if (isset($user['birthday']) && $user['birthday']) {
                                    $lPublics = new \app\api\service\UserService();
                                    $title = '团长奖励获得吃豆';
                                    $desc = '您的好友'.$user['nickname'].'完成第'.$order_num.'单，奖励您'.$amount.'吃豆';
                                    $url = '/pages/user/user-data';
                                    $res = $lPublics->pushChat($user1['birthday'],$title,$desc,$url,$user1['id']);
                                // }
                            }
                        }
                        // 用户加积分
                        $res = (new User())->score(config('order_score'),$row['user_id'],'下单获得');
                        if (!$res) {Db::rollback();$this->error('增加积分失败');}
                        // 完成订单
                        \app\common\model\UserLuckdrawLog::addLog($row['user_id'], 1, $play_order_no, '完成订单', 2);
                    }
                } elseif (isset($row['order_status']) && in_array($row['order_status'], [6,3]) && $params['state']==4) {
                    // 备注不是必填
                    $orderProof = orderProof::where(['play_order_no'=>$play_order_no,'handle_status'=>1])->order('id DESC')->find();
                    // 产生售后事件
                    $OrderAftersaleId = $this->OrderAftersale($nickname,$id,'三方提交异常',$orderProof['play_order_no'],$row['play_no'],json_encode(['desc'=>$params['reason'],'img'=>'','remark'=>$params['reason']],JSON_UNESCAPED_UNICODE));

                    $orderProof->handle_status = 0;
                    $orderProof->yc_remark = $params['reason'];
                    $orderProof->order_aftersale_id = $OrderAftersaleId;
                    $orderProof->handle_merchant_id = $id;
                    $orderProof->handle_merchant_desc = json_encode(['desc'=>$params['reason'],'img'=>'','remark'=>$params['reason']],JSON_UNESCAPED_UNICODE);
                    $orderProof->save();
                    // 订单状态
                    $row->order_status = -7;
                    $row->update_by = $id;
                    $row->save();
                    $this->orderLog($row->id,$play_order_no,'三方提交异常',$nickname,$id);
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
            }
        }
    }


    public function notify1()
    {
        $params = $this->request->param();
        \think\Log::write('报名回调'.json_encode($params));
        $nickname='三方商家';
        $id=999;
        $param = '{"order_sn":"E240604201924C91590","user_order_sn":"801082730138670839","paid_amount":"28.36","commission_type":"2","commission":"6","commission_ratio":"31.04","e_commission":"8.81","e_commission_ratio":"31.04","state":"3","internal_state":"8","source":"1","user_source":"","promotion_id":"yz-68197110-145818-170907","reason":"","expire_time":"1716307199","create_time":"2024-05-21 21:32:14","place_order_time":"2024-05-21 21:34:28","finished_time":"2024-05-21 21:56:18","reject_type":"0","update_time":"2024-05-21 21:56:18"}';
        $params = json_decode($param,1);
        if ($params['source']!=2) {
            $platform_order_no = $params['order_sn'];
            $mtofficial_order = \app\common\model\Mtorder::where(['play_order_no'=>$platform_order_no])->find();
            if (isset($mtofficial_order['content']) && $mtofficial_order['content']) {
                $content = json_decode($mtofficial_order['content'],1);
            }
            if (isset($content['shop_origin_id']) && $mtofficial_order) {
                list($play,$shop) = (new \app\api\service\PlayService())->mtofficial($mtofficial_order['play_no'],$mtofficial_order['cps_id'],$content);
                //用户任务状态编码(状态  1：已报名 2：审核中 3：已完成 4已驳回 5 已取消 6已过期)
                switch ($params['state']) {
                    case 6:
                        $mtofficial_order->order_status=-2;
                        break;
                    case 5:
                        $mtofficial_order->order_status=-1;
                        break;
                    case 1:
                        $mtofficial_order->user_pay = (float)$params['paid_amount'];
                        if ($mtofficial_order['is_yunzhan']!=3) {
                            $ratio = $play['ratio']/100;
                            $actual_rebate_amt = round($params['paid_amount']*$ratio/100,2);
                            $maxCommission = $play['maxCommission']/100;
                            if ($actual_rebate_amt>$maxCommission) {
                                $actual_rebate_amt = $maxCommission;
                            }
                            $mtofficial_order->actual_rebate_amt = (float)$actual_rebate_amt;
                            $mtofficial_order->rebate_amt = (float)$params['commission'];
                            $mtofficial_order->service_charge_amt = round($params['commission']-$actual_rebate_amt,2);
                        } else {
                            $mtofficial_order->actual_rebate_amt = (float)$params['commission']-$play['service_amt'];
                            $mtofficial_order->rebate_amt = (float)$params['commission'];
                            $mtofficial_order->service_charge_amt = $play['service_amt'];
                        }
                        $mtofficial_order->pay_time = strtotime($params['place_order_time']);
                        $mtofficial_order->expire_time = time() + 21600;
                        // 过期时间最晚到第二天0点
                        $dayend = strtotime(date('Ymd'))+86399;
                        if ($mtofficial_order->expire_time>$dayend) {
                            $mtofficial_order->expire_time=$dayend;
                        }
                        $mtofficial_order->order_status=4;
                        break;
                    case 2:
                        if ($params['internal_state']==4) {
                            $mtofficial_order->user_pay = (float)$params['paid_amount'];
                            $ratio = $play['ratio']/100;
                            $actual_rebate_amt = round($params['paid_amount']*$ratio/100,2);
                            $maxCommission = $play['maxCommission']/100;
                            if ($actual_rebate_amt>$maxCommission) {
                                $actual_rebate_amt = $maxCommission;
                            }
                            $mtofficial_order->actual_rebate_amt = (float)$actual_rebate_amt;
                            $mtofficial_order->rebate_amt = (float)$params['commission'];
                            $mtofficial_order->service_charge_amt = round($params['commission']-$actual_rebate_amt,2);
                            $mtofficial_order->pay_time = strtotime($params['place_order_time']);
                            $mtofficial_order->expire_time = strtotime(date('Y-m-d'))+86400*2-1;  // 报名后过期时间第二天24点
                            $mtofficial_order->order_status=4;
                        }
                        break;
                    case 3:
                        $mtofficial_order->user_pay = (float)$params['paid_amount'];
                        if ($mtofficial_order['is_yunzhan']!=3) {
                            $ratio = $play['ratio']/100;
                            $actual_rebate_amt = round($params['paid_amount']*$ratio/100,2);
                            $maxCommission = $play['maxCommission']/100;
                            if ($actual_rebate_amt>$maxCommission) {
                                $actual_rebate_amt = $maxCommission;
                            }
                            $mtofficial_order->actual_rebate_amt = (float)$actual_rebate_amt;
                            $mtofficial_order->rebate_amt = (float)$params['commission'];
                            $mtofficial_order->service_charge_amt = round($params['commission']-$actual_rebate_amt,2);
                        } else {
                            $mtofficial_order->actual_rebate_amt = (float)$params['commission']-$play['service_amt'];
                            $mtofficial_order->rebate_amt = (float)$params['commission'];
                            $mtofficial_order->service_charge_amt = $play['service_amt'];
                        }
                        $mtofficial_order->pay_time = strtotime($params['place_order_time']);
                        $mtofficial_order->order_status=3;
                        break;
                }
                Db::startTrans();
                try {
                    $mtofficial_order->save();
                    if (in_array($params['state'], [3])) {
                        $User = new \app\common\model\User();
                        $user = \app\common\model\User::where('id',$mtofficial_order['user_id'])->find();
                        // 用户获得吃豆
                        $beans = $mtofficial_order['actual_rebate_amt'];
                        $user->beans($beans,$mtofficial_order['user_id'],'下单返豆',$mtofficial_order['play_order_no']);
                        \app\common\model\MtorderLog::create([
                            'play_order_id' => $mtofficial_order['id'],
                            'play_order_no' => $mtofficial_order['play_order_no'],
                            // 'create_by' => $nickname,
                            'create_by_id' => $mtofficial_order['user_id'],
                            'is_front' => 1,
                            'info' => '订单完成',
                        ]);
                        // 发送微信消息
                        $qywx = Db::name('qywx_receive')->where('user_id',$user['id'])->field('id,UserID,ExternalUserID')->find();
                        if ($qywx) {
                            $external_userid = $qywx['ExternalUserID'];
                            $sender = $qywx['UserID'];
                            $title = '您的活动订单审核成功';
                            $picurl = config('upload_domain').'/uploads/20230422/baca91c2f33a6d1270aae65ea4d3dc79.png';
                            $desc = '恭喜完成订单，获得'.$beans.'吃豆';
                            $url = config('h5_domain').'/#/pages/index/order';
                            $lPublics = new \app\api\service\UserService();
                            $res = $lPublics->qywxPush($external_userid,$sender,$title,$picurl,$desc,$url,$user['id']);
                        }
                        // 发送app消息
                        // if (isset($user['birthday']) && $user['birthday']) {
                            $lPublics = new \app\api\service\UserService();
                            $title = '您的活动订单审核成功';
                            $desc = '恭喜完成订单，获得'.$beans.'吃豆';
                            $url = '/pages/index/order';
                            $res = $lPublics->pushChat($user['birthday'],$title,$desc,$url,$user['id'],$mtofficial_order->play_order_no);
                            $title = '【完成一笔订单】任务达成';
                            $desc = '获得2次抽奖机会（当日有效）';
                            $url = '/index/raffle/raffle';
                            $res = $lPublics->pushChat($user['birthday'],$title,$desc,$url,$user['id']);
                        // }
                        // 分销和抽奖机会和积分
                        // if ($order->order_status==3) {
                            if ($user['pid']) {
                                $order_num = order_count($mtofficial_order['user_id']);
                                if ($order_num==1) {
                                    $amount = (int)Db::name('config')->where('name','first_order')->value('value');
                                    // 上级用户新增有效团员
                                    \app\common\model\UserLuckdrawLog::addLog($user['pid'], 1, $mtofficial_order['play_order_no'], '新增有效团员');
                                    // 如果是第一单，则上级用户获得一个有效用户，加积分
                                    $res = $User->score(config('invite_score'),$user['pid'],'邀请获得');
                                    if (!$res) {Db::rollback();$this->error('上级用户获取积分失败');}
                                    // unipush
                                    $user2 = $User->get($user['pid']);
                                    // if (isset($user2['birthday']) && $user2['birthday']) {
                                        $lPublics = new \app\api\service\UserService();
                                        $title = '【新增一位有效团员】任务达成';
                                        $desc = '获得1次抽奖机会（当日有效）';
                                        $url = '/index/raffle/raffle';
                                        $res = $lPublics->pushChat($user2['birthday'],$title,$desc,$url,$user2['id']);
                                    // }
                                } elseif ($order_num==2) {
                                    $amount = (int)Db::name('config')->where('name','second_order')->value('value');
                                } else {
                                    $rate = (int)\think\Config::get('site.third_order');
                                    $amount = round($mtofficial_order['service_charge_amt']*$rate*0.01,2);
                                    // 当前是不是会员团长
                                    $user1 = \app\common\model\User::get($user['pid']);
                                    if ($user1['hytz']==1) {
                                        // 团长的有效用户数是否大于指定的用户数
                                        $invitation_new_reward = \think\Config::get('site.yyty');
                                        $user_distribution = Db::name('user_distribution')->field('uid')->where(['pid'=>$user['pid'],'status'=>1])->group('uid')->select();
                                        if (count($user_distribution)>$invitation_new_reward) {
                                            $ratenim = (float)\think\Config::get('site.third_order_min3');
                                        } else {
                                            $ratenim = (float)\think\Config::get('site.third_order_min2');
                                        }
                                    } else {
                                        $ratenim = (float)\think\Config::get('site.third_order_min');
                                    }
                                    if ($amount<$ratenim) $amount = $ratenim;
                                }
                                if ($amount) {
                                    \app\common\model\UserDistribution::create([
                                        'play_order_no' => $mtofficial_order['play_order_no'],
                                        'uid' => $mtofficial_order['user_id'],
                                        'pid' => $user['pid'],
                                        'play_no' => $mtofficial_order['play_no'],
                                        'amount' => $amount,
                                        'order_times' => $order_num,
                                    ]);
                                    // 上级用户加吃豆
                                    $res = $User->beans($amount, $user['pid'], '下级返利', $mtofficial_order['play_order_no']);
                                    if (!$res) {Db::rollback();$this->error('上级返利失败');}
                                    // 发送app消息
                                    // $user = \app\common\model\User::get($user['pid']);
                                    if (!isset($user1)) $user1 = \app\common\model\User::get($user['pid']);
                                    // if (isset($user['birthday']) && $user['birthday']) {
                                        $lPublics = new \app\api\service\UserService();
                                        $title = '团长奖励获得吃豆';
                                        $desc = '您的好友'.$user['nickname'].'完成第'.$order_num.'单，奖励您'.$amount.'吃豆';
                                        $url = '/pages/user/user-data';
                                        $res = $lPublics->pushChat($user1['birthday'],$title,$desc,$url,$user1['id']);
                                    // }
                                }
                            }
                            // 用户加积分
                            $res = $User->score(config('order_score'),$mtofficial_order['user_id'],'下单获得');
                            if (!$res) {Db::rollback();$this->error('增加积分失败');}
                            // 完成订单
                            \app\common\model\UserLuckdrawLog::addLog($mtofficial_order['user_id'], 1, $mtofficial_order['play_order_no'], '完成订单', 2);
                        // }
                    }
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                }
            }
        } else {
            Db::startTrans();
            try {
                // 三方招商，待商家复审完成
                $row = OrderModel::where('yunzhan_order_no',$params['order_sn'])->find();
                $play_order_no = $params['order_sn'];
                if (isset($row['order_status']) && $row['order_status']==6 && $params['state']==3) {
                    $User = new \app\common\model\User();
                    $play = PlayModel::where(['play_no'=>$row['play_no']])->lock(true)->find();
                    $orderProof = OrderProof::where(['play_order_no'=>$play_order_no])->order('id DESC')->find();
                    if (!$orderProof) {
                        $this->error('提交有误');
                    }
                    $beans = $row->actual_rebate_amt;
                    $User->beans($beans,$row['user_id'],'下单返豆',$orderProof['play_order_no']);
                    // 实际返豆
                    $row->actual_rebate_amt = $beans;
                    // 订单状态
                    $row->order_status = 3;
                    $row->update_by = $id;
                    $row->save();
                    $this->orderLog($row->id,$play_order_no,'客服审核通过',$nickname,$id);
                    // 消息处理
                    $user = $User->get($row['user_id']);
                    // 发送微信消息
                    $qywx = Db::name('qywx_receive')->where('user_id',$user['id'])->field('id,UserID,ExternalUserID')->find();
                    if ($qywx) {
                        $external_userid = $qywx['ExternalUserID'];
                        $sender = $qywx['UserID'];
                        $title = '您的活动订单审核成功';
                        $picurl = config('upload_domain').'/uploads/20230422/baca91c2f33a6d1270aae65ea4d3dc79.png';
                        $desc = '恭喜完成订单，获得'.$beans.'吃豆';
                        $url = config('h5_domain').'/#/pages/index/order';
                        $lPublics = new \app\api\service\UserService();
                        $res = $lPublics->qywxPush($external_userid,$sender,$title,$picurl,$desc,$url,$user['id']);
                    }
                    // 发送app消息
                    // if (isset($user['birthday']) && $user['birthday']) {
                        $lPublics = new \app\api\service\UserService();
                        $title = '您的活动订单审核成功';
                        $desc = '恭喜完成订单，获得'.$beans.'吃豆';
                        $url = '/pages/index/order';
                        $res = $lPublics->pushChat($user['birthday'],$title,$desc,$url,$user['id'],$play_order_no);
                        $title = '【完成一笔订单】任务达成';
                        $desc = '获得2次抽奖机会（当日有效）';
                        $url = '/index/raffle/raffle';
                        $res = $lPublics->pushChat($user['birthday'],$title,$desc,$url,$user['id']);
                    // }
                    // 发送短信
                    // if (isset($user['mobile']) && $user['mobile']) {
                    //     $Alisms = new \addons\alisms\Alisms();
                    //     $params = [
                    //         'mobile' => $user['mobile'],
                    //         'event' => 'order_complete',
                    //         'msg' => '您好，您在吃喝不愁平台参加的外卖活动订单已通过，请知晓。',
                    //     ];
                    //     $Alisms->smsNotice($params);
                    // }
                    // 订阅消息
                    $openid = Db::name('third')->where(['user_id'=>$user['id'],'platform'=>'miniprogram'])->value('openid');
                    if ($openid) {
                        $UserService = new \app\api\service\UserService();
                        $template_id = config('template_id.ddwctz');
                        $page = '/pages/index/order';
                        $data = [
                            'thing1' => ['value'=>$row->shop_name],
                            'time3' => ['value'=>date('Y-m-d H:i:s')],
                            'character_string5' => ['value'=>$play_order_no],
                            'phrase10' => ['value'=>'已完成'],
                        ];
                        $res = $UserService->xcxNotice($openid,$template_id,$page,$data);
                    }
                    // 分销和抽奖机会和积分
                    if ($row->order_status==3) {
                        // 中间人佣金
                        if ($play['is_pay']==1) {
                            $shop = Db::name('shop')->where(['shop_no'=>$row['shop_no']])->field('middleman_id,shop_no')->find();
                            $middleman = Db::name('middleman')->where(['id'=>$shop['middleman_id']])->field('rebate_amt,user_id')->find();
                            if (isset($middleman['rebate_amt']) && $middleman['rebate_amt']) {
                                (new \app\common\model\User())->money($middleman['rebate_amt'], $middleman['user_id'], '经纪人收益', $play_order_no);
                            }
                        }
                        $this->orderLog($row->id,$play_order_no,'订单完成',$nickname,$id);
                        if ($user['pid']) {
                            $order_num = order_count($row['user_id']);
                            if ($order_num==1) {
                                $amount = (int)Db::name('config')->where('name','first_order')->value('value');
                                // 上级用户新增有效团员
                                \app\common\model\UserLuckdrawLog::addLog($user['pid'], 1, $play_order_no, '新增有效团员');
                                // 如果是第一单，则上级用户获得一个有效用户，加积分
                                $res = (new User())->score(config('invite_score'),$user['pid'],'邀请获得');
                                if (!$res) {Db::rollback();return false;}
                                // unipush
                                $user2 = $User->get($user['pid']);
                                if (isset($user2['birthday']) && $user2['birthday']) {
                                    $lPublics = new \app\api\service\UserService();
                                    $title = '【新增一位有效团员】任务达成';
                                    $desc = '获得1次抽奖机会（当日有效）';
                                    $url = '/index/raffle/raffle';
                                    $res = $lPublics->pushChat($user2['birthday'],$title,$desc,$url,$user2['id']);
                                }
                            } elseif ($order_num==2) {
                                $amount = (int)Db::name('config')->where('name','second_order')->value('value');
                            } else {
                                $rate = (int)\think\Config::get('site.third_order');
                                $amount = round($row['service_charge_amt']*$rate*0.01,2);
                                // 当前是不是会员团长
                                $user1 = \app\common\model\User::get($user['pid']);
                                if ($user1['hytz']==1) {
                                    // 团长的有效用户数是否大于指定的用户数
                                    $invitation_new_reward = \think\Config::get('site.yyty');
                                    $user_distribution = Db::name('user_distribution')->field('uid')->where(['pid'=>$user['pid'],'status'=>1])->group('uid')->select();
                                    if (count($user_distribution)>$invitation_new_reward) {
                                        $ratenim = (float)\think\Config::get('site.third_order_min3');
                                    } else {
                                        $ratenim = (float)\think\Config::get('site.third_order_min2');
                                    }
                                } else {
                                    $ratenim = (float)\think\Config::get('site.third_order_min');
                                }
                                if ($amount<$ratenim) $amount = $ratenim;
                            }
                            if ($amount) {
                                \app\common\model\UserDistribution::create([
                                    'play_order_no' => $play_order_no,
                                    'uid' => $row['user_id'],
                                    'pid' => $user['pid'],
                                    'play_no' => $row['play_no'],
                                    'amount' => $amount,
                                    'order_times' => $order_num,
                                ]);
                                // 上级用户加吃豆
                                $res = (new User())->beans($amount, $user['pid'], '下级返利', $play_order_no);
                                if (!$res) {Db::rollback();return false;}
                                // 发送app消息
                                if (!isset($user1)) $user1 = \app\common\model\User::get($user['pid']);
                                // if (isset($user['birthday']) && $user['birthday']) {
                                    $lPublics = new \app\api\service\UserService();
                                    $title = '团长奖励获得吃豆';
                                    $desc = '您的好友'.$user['nickname'].'完成第'.$order_num.'单，奖励您'.$amount.'吃豆';
                                    $url = '/pages/user/user-data';
                                    $res = $lPublics->pushChat($user1['birthday'],$title,$desc,$url,$user1['id']);
                                // }
                            }
                        }
                        // 用户加积分
                        $res = (new User())->score(config('order_score'),$row['user_id'],'下单获得');
                        if (!$res) {Db::rollback();$this->error('增加积分失败');}
                        // 完成订单
                        \app\common\model\UserLuckdrawLog::addLog($row['user_id'], 1, $play_order_no, '完成订单', 2);
                    }
                } elseif (isset($row['order_status']) && in_array($row['order_status'], [6,3]) && $params['state']==4) {
                    // 备注不是必填
                    $orderProof = orderProof::where(['play_order_no'=>$play_order_no,'handle_status'=>1])->order('id DESC')->find();
                    // 产生售后事件
                    $OrderAftersaleId = $this->OrderAftersale($nickname,$id,'三方提交异常',$orderProof['play_order_no'],$row['play_no'],json_encode(['desc'=>$params['reason'],'img'=>'','remark'=>$params['reason']],JSON_UNESCAPED_UNICODE));

                    $orderProof->handle_status = 0;
                    $orderProof->yc_remark = $params['reason'];
                    $orderProof->order_aftersale_id = $OrderAftersaleId;
                    $orderProof->handle_merchant_id = $id;
                    $orderProof->handle_merchant_desc = json_encode(['desc'=>$params['reason'],'img'=>'','remark'=>$params['reason']],JSON_UNESCAPED_UNICODE);
                    $orderProof->save();
                    // 订单状态
                    $row->order_status = -7;
                    $row->update_by = $id;
                    $row->save();
                    $this->orderLog($row->id,$play_order_no,'三方提交异常',$nickname,$id);
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
            }
        }
    }

    public function orderLog($play_order_id, $play_order_no, $info, $create_by, $create_by_id, $is_front=2)
    {
        Db::startTrans();
        try {
            OrderLog::create([
                'play_order_id' => $play_order_id,
                'play_order_no' => $play_order_no,
                'info' => $info,
                'create_by' => $create_by,
                'create_by_id' => $create_by_id,
                'is_front' => $is_front,
            ]);
            Db::commit();
            return true;
        } catch (ValidateException $e) {
            Db::rollback();
            return false;
        } catch (PDOException $e) {
            Db::rollback();
            return false;
        } catch (Exception $e) {
            Db::rollback();
            return false;
        }
    }

    public function OrderAftersale($submit_user, $submit_user_id, $type, $play_order_no, $play_no, $content)
    {
        Db::startTrans();
        try {
            $OrderAftersale = new OrderAftersale();
            $OrderAftersale->save([
                'submit_user' => $submit_user,
                'submit_user_id' => $submit_user_id,
                'type' => $type,
                'play_order_no' => $play_order_no,
                'play_no' => $play_no,
                'content' => $content,
            ]);
            Db::commit();
            return $OrderAftersale['id'];
        } catch (ValidateException $e) {
            Db::rollback();
            return false;
        } catch (PDOException $e) {
            Db::rollback();
            return false;
        } catch (Exception $e) {
            Db::rollback();
            return false;
        }
    }


    public function txNotify()
    {
        $params = $this->request->param();
        // $res = '{"id":"d0fdf54b-6ba6-5c86-a8c4-3689a0b104ca","create_time":"2024-05-18T14:02:05+08:00","resource_type":"encrypt-resource","event_type":"MCHTRANSFER.BATCH.FINISHED","summary":"\u5546\u5bb6\u8f6c\u8d26\u6279\u6b21\u5b8c\u6210\u901a\u77e5","resource":{"original_type":"mch_payment","algorithm":"AEAD_AES_256_GCM","ciphertext":"ajBUlvD6cttKvD1VhsTCDn3\/IN5VAdkNu1pOiqBPckxjzr\/hzKkuDYlidGxYSnmnHkGfgPLRicoRkDr7cjRAOJfMDQ9IS8x2Fzgytoq9Y1ps7A8+99gxR+EfzJnCpnPMKXa821ETEUcGuRhiIMi9gP4nJUPS7AiOewXkcX0J\/syUWIJEZRo2oaF5MhmIs5ufS9A2kewowx4el\/1q4+nAJ41T\/5494EGp9bqVMjs45NOM97cQV\/Ja4PuKDOszt8GzGmgpUuf5xtFK6SA6F1noj6AejjC5vu6SRa5aulgzB7NwIb9MQs+a\/eZ+dOixc0ixa1wZIM5BORPRgkLbgc4\/RyurdTg+UNJmALn1Vm\/VuU0gTNHueZ7NzSdH+07n1ISLve1Ip5zdzSs6ZmD9fljcGUHSxSoOD2Pwng==","associated_data":"mch_payment","nonce":"W0pQlzafu0QN"}}';
        // $params = json_decode($res,1);
        \think\Log::write('转账回调'.json_encode($params));
        $key = 'syjkouHGYTDG89754JHNdesspolk8904';
        // $decrypted = '{"out_batch_no":"595130427277","batch_id":"131000701058501691086842024022972600665912","batch_status":"FINISHED","total_num":1,"total_amount":100,"success_amount":100,"success_num":1,"fail_amount":0,"fail_num":0,"mch_id":"1644161646","update_time":"2024-05-17T13:52:36+08:00","mchid":"1644161646"}';
        $decrypted = sodium_crypto_aead_aes256gcm_decrypt(base64_decode($params['resource']['ciphertext']),$params['resource']['associated_data'],$params['resource']['nonce'],$key);
        $decrypted = json_decode($decrypted,1);
        Db::startTrans();
        try {
            if (!$decrypted['fail_amount'] && !$decrypted['fail_num']) {
                $user_withdrawal_log = Db::name('user_withdrawal_log')->where(['withdrawal_no'=>$decrypted['out_batch_no']])->find();
                // 审核通过
                Db::name('user_withdrawal_log')->where(['withdrawal_no'=>$decrypted['out_batch_no']])->update(['log_status'=>1,'update_dt'=>date('Y-m-d H:i:s',strtotime($decrypted['update_time']))]);
                if ($user_withdrawal_log['is_merchant']==2) {
                    $beans = -1*$user_withdrawal_log['wallet'];
                    $res = (new User())->beans($beans, $user_withdrawal_log['user_id'], '吃豆提现', $user_withdrawal_log['id']);
                } elseif ($user_withdrawal_log['is_merchant']==0) {
                    //冻结金额扣除
                    $money = -1*$user_withdrawal_log['wallet'];
                    User::money($money, $user_withdrawal_log['user_id'], '提现通过', $user_withdrawal_log['id'], 1);
                } elseif ($user_withdrawal_log['is_merchant']==3) {
                    //冻结金额扣除
                    $money = -1*$user_withdrawal_log['wallet'];
                    User::money($money, $user_withdrawal_log['user_id'], '提现通过', $user_withdrawal_log['id'], 1);
                }
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
    }


    public function getOrderInfo()
    {
        $bwc = new \services\BwcService();
        $telephone='15216674268';
        $order_sn='T240604173357S69173';
        $res = $bwc->getOrderInfo($telephone,$order_sn);
        var_dump($res);exit;
    }


    public function orderCancel()
    {
        $yunzhan_order_no = 'T240525103845T70008';
        $mobile = '15195813223';
        $bwc = new \services\BwcService();
        $res = $bwc->unApply($yunzhan_order_no,$mobile);
        var_dump($res);exit;
        \think\Log::write('取消报名：'.$res);
    }




    public function mtReport()
    {
        $date = input('date','');
        if ($date) {
            $time = strtotime($date);
        } else {
            $time = time();
            $date = date('Y-m-d H:i:s',$time);
        }
        $MeituanService = new \services\MeituanService('','');
        $res = $MeituanService->loadorder($time); // 获取前一天的账单
        // $res = '{"retStatus":0,"downloadUrl":"https://s3plus.sankuai.com/dsp-middlepage-offline-data/cps-api-order-check/8ba6eeedf4a74c1f9975ac6e0863326c-20240621-order-check-data.txt?AWSAccessKeyId=f100f57756364e78a5bc40bdfa9251ac&Expires=1718968433&Signature=dul6oXxLLmLVU81L2u1mhb%2BmZG0%3D","message":"success"}';
        $decode = json_decode($res,1);
        if (isset($decode['downloadUrl'])) {
            $content = file_get_contents($decode['downloadUrl']);
            $content = str_replace('}', '},', $content);
            $content = trim($content);
            $content = trim($content,',');
            $content = '['.$content.']';
            $decode = json_decode($content,1);
            $all = [];
            foreach ($decode as $key => $value) {
                $value['create_dt'] = $date;
                $all[] = $value;
            }
            Db::name('mtofficial_report')->insertAll($all);
        }
    }

}
